from django.shortcuts import render
from HP_ONHOLD.models import *
from django.template.loader import get_template
from django.template import Context
from django.http import HttpResponse
import json
from EMC.public import *
import xlrd
import uuid

# Create your views here.
def hponhold_main(request):
    t = get_template('../templates/HP_ONHOLD/HP_ONHOLD.tpl')
    html = t.render(Context({'current_date': 'ADMIN'}))
    return HttpResponse(html)

def handle_uploaded_file(f):
    filename = 'Temp/'+str(uuid.uuid1())+'.xls'
    destination = open(filename, 'wb+')
    for chunk in f.chunks():
        destination.write(chunk)
    destination.close()
    return filename

def hponhold_main_upload_post(request):
    result = CMessage("UPLOAD","Fail to import the file","Unknown")    
    try:
        if request.method == 'POST':
            if len(request.FILES) > 0:
                filename = handle_uploaded_file(request.FILES['uploadfile'])
                result = readxls(filename)
            else:
                result = CMessage("UPLOAD","No file is uploaded","Unknown")
    except Exception as e:
        result = e[1]
    return HttpResponse(result.ToJson())

def readxls(filename):
    err = "unknown"
    counts = {'inserted':0,'updated':0}
    data = xlrd.open_workbook(filename)
    table = data.sheets()[0]
    tran = CDateTran()
    try:
        for rownum in range(1,table.nrows):        
            row = table.row_values(rownum)
            valid_reason = Reason.objects.filter(ONHOLD_REASON_DESC=row[4]).count()
            if valid_reason >0:
                record = WIP.objects.filter(CUSTOMER_PO=row[2]).count()
                if record > 0:
                    WIP.objects.filter(CUSTOMER_PO=row[2]).update(ORDER_NR=row[0],REASON=Reason.objects.get(ONHOLD_REASON_DESC=row[4]),KEYIN_DATE=tran.getdate(row[1]),CUSTOMER_PO=row[2],WAIT_MEMO=row[5],STATUS=row[6],PRODUCT_TYPE=row[7],TRAN_OWNER=row[8],TAT=row[9],CLOSED_DATE=tran.getdate(row[10]),REPAIR_ETA=row[11],ESCALATION_FEEDBACK=row[12],PART_ARRIVAL_ETA=row[13],ROOT_CAUSE=row[14],SOLUTION=row[15])
                    counts['updated'] += 1
                else:
                    WIP.objects.create(ORDER_NR=row[0],REASON=Reason.objects.get(ONHOLD_REASON_DESC=row[4]),KEYIN_DATE=tran.getdate(row[1]),CUSTOMER_PO=row[2],SERIAL_NR=row[3],WAIT_MEMO=row[5],STATUS=row[6],PRODUCT_TYPE=row[7],TRAN_OWNER=row[8],TAT=row[9],CLOSED_DATE=tran.getdate(row[10]),REPAIR_ETA=row[11],ESCALATION_FEEDBACK=row[12],PART_ARRIVAL_ETA=row[13],ROOT_CAUSE=row[14],SOLUTION=row[15])
                    counts['inserted'] += 1
                err = "SUCCEED"
            else:
                err = "Wait reason is invalid!"
                continue
            #record = WIP(ORDER_NR=row[0],REASON=Reason.objects.get(ONHOLD_REASON_DESC=row[4]),KEYIN_DATE=row[1],CUSTOMER_PO=row[2],SERIAL_NR=row[3],WAIT_MEMO=row[5],STATUS=row[6],PRODUCT_TYPE=row[7],TRAN_OWNER=row[8],TAT=row[9],CLOSED_DATE=row[10],REPAIR_ETA=row[11],ESCALATION_FEEDBACK=row[12],PART_ARRIVAL_ETA=row[13],ROOT_CAUSE=row[14],SOLUTION=row[15])
            #record.save()
    except Exception as e:
        print e[1]
    message = CMessage("UPLOAD","Result(Inserted: %d, updated: %d)" % (counts['inserted'],counts['updated']),err)
    return message

def hponhold_get(request):
    result = []
    result1 = {}
    try:
        table = WIP.objects.query_WIP()
        for row in table:
            result.append({"ONHOLD_WIP_ID":row["ONHOLD_WIP_ID"],"ORDER_NR":row["ORDER_NR"], "KEYIN_DATE":row["KEYIN_DATE"], "CUSTOMER_PO":row["CUSTOMER_PO"], "SERIAL_NR":row["SERIAL_NR"],"ONHOLD_REASON_DESC":row["ONHOLD_REASON_DESC"],"STATUS":row["STATUS"],"TAT":row["TAT"],"WAIT_MEMO":row["WAIT_MEMO"],"PRODUCT_TYPE":row["PRODUCT_TYPE"], "TRAN_OWNER":row["TRAN_OWNER"], "CLOSED_DATE":row["CLOSED_DATE"],"REPAIR_ETA":row["REPAIR_ETA"],"ESCALATION_FEEDBACK":row["ESCALATION_FEEDBACK"],"PART_ARRIVAL_ETA":row["PART_ARRIVAL_ETA"],"ROOT_CAUSE":row["ROOT_CAUSE"],"SOLUTION":row["SOLUTION"],"CT_DT":row["CT_DT"],"MD_DT":row["MD_DT"],})
        result1 = {"total":len(result),"rows":result}
    except Exception as e:
        print e[0]
    return HttpResponse(json.dumps(result1))


def hponhold_post(request):
    counts = {'inserted':0,'updated':0}
    error = ""
    try:
        if 'inserted' in request.POST and request.POST['inserted']:
            insertdata = request.POST['inserted']
            if len(insertdata) > 0:
                for row in json.loads(insertdata):
                    insertrow = WIP.objects.create(ORDER_NR=row["ORDER_NR"],REASON_ID=Reason.objects.get(ONHOLD_REASON_DESC=row["ONHOLD_REASON_DESC"])["REASON_ID"],KEYIN_DATE=row["KEYIN_DATE"],CUSTOMER_PO=row["CUSTOMER_PO"],SERIAL_NR=row["SERIAL_NR"],STATUS=row["STATUS"],TAT=row["TAT"],WAIT_MEMO=row["WAIT_MEMO"],PRODUCT_TYPE=row["PRODUCT_TYPE"],TRAN_OWNER=row["TRAN_OWNER"],CLOSED_DATE=row["CLOSED_DATE"],REPAIR_ETA=row["REPAIR_ETA"],ESCALATION_FEEDBACK=row["ESCALATION_FEEDBACK"],PART_ARRIVAL_ETA=row["PART_ARRIVAL_ETA"],ROOT_CAUSE=row["ROOT_CAUSE"],SOLUTION=row["SOLUTION"])
                    counts['inserted'] +=1
        if 'updated' in request.POST and request.POST['updated']:
            updatedata = request.POST['updated']
            if len(updatedata) > 0:
                for row in json.loads(updatedata):
                    if WIP.objects.filter(ONHOLD_WIP_ID=row["ONHOLD_WIP_ID"]).update(WAIT_MEMO=row['WAIT_MEMO'],STATUS=row["STATUS"],REASON=Reason.objects.get(ONHOLD_REASON_DESC=row["ONHOLD_REASON_DESC"]),TAT=row["TAT"],PRODUCT_TYPE=row["PRODUCT_TYPE"],TRAN_OWNER=row["TRAN_OWNER"],CLOSED_DATE=row["CLOSED_DATE"],REPAIR_ETA=row["REPAIR_ETA"],ESCALATION_FEEDBACK=row["ESCALATION_FEEDBACK"],PART_ARRIVAL_ETA=row["PART_ARRIVAL_ETA"],ROOT_CAUSE=row["ROOT_CAUSE"],SOLUTION=row["SOLUTION"])>0:
                        counts['updated'] +=1
    except Exception as e:
        error = e[1]
        print error
    message = CMessage("HP ONHOLD","Result(Inserted: %d, updated: %d)" % (counts['inserted'],counts['updated']),error)
    return HttpResponse( message.ToJson())

def hponhold_get_wait_reason(request):
    result = []
    try:
        table = Reason.objects.all()
        for row in table:
            result.append({"reason_id":row.REASON_ID, "reason_desc":row.ONHOLD_REASON_DESC})
    except Exception as e:
        print e[1]
    print result
    return HttpResponse(json.dumps(result))
    
    

#remove this solution
"""def hponhold_detail(request, offset):
    wipid = int(offset)
    print wipid
    strHtml ="<style type=\"text/css\">.dv-table td{border:0;} .dv-label{	font-weight:bold;color:#15428B;	width:100px;}</style><table class=\"dv-table\" border=\"0\" style=\"width:100%;\"><tr>"; 
    try:
        result = []
        result1 = {}
        detailrow1 = []
        detailrow2 = []
        table = WIP.objects.query_WIP_by_id(wipid)
        for row in table:
            detailrow1.append({"WAIT_MEMO":row["WAIT_MEMO"],"PRODUCT_TYPE":row["PRODUCT_TYPE"], "TRAN_OWNER":row["TRAN_OWNER"], "CLOSED_DATE":row["CLOSED_DATE"],"REPAIR_ETA":row["REPAIR_ETA"],"ESCALATION_FEEDBACK":row["ESCALATION_FEEDBACK"],})
        for row in table:
            detailrow2.append({"PART_ARRIVAL_ETA":row["PART_ARRIVAL_ETA"],"ROOT_CAUSE":row["ROOT_CAUSE"],"SOLUTION":row["SOLUTION"],"CT_DT":row["CT_DT"],"MD_DT":row["MD_DT"],})
           
        for row in detailrow1:
            for (key,value) in row.items():
                strHtml = strHtml + "<td class=\"dv-label\">" + key +": </td><td>" +str(value) +"</td>"
        strHtml = strHtml + "</tr><tr>"
        for row in detailrow2:
            for (key,value) in row.items():
                strHtml = strHtml + "<td class=\"dv-label\">" + key +": </td><td>" +str(value) +"</td>"
               
            #result.append({"WAIT_MEMO":row["WAIT_MEMO"],"PRODUCT_TYPE":row["PRODUCT_TYPE"], "TRAN_OWNER":row["TRAN_OWNER"], "CLOSED_DATE":row["CLOSED_DATE"],"REPAIR_ETA":row["REPAIR_ETA"],"ESCALATION_FEEDBACK":row["ESCALATION_FEEDBACK"],"PART_ARRIVAL_ETA":row["PART_ARRIVAL_ETA"],"ROOT_CAUSE":row["ROOT_CAUSE"],"SOLUTION":row["SOLUTION"],"CT_DT":row["CT_DT"],"MD_DT":row["MD_DT"],})
        #result1 = {"total":len(result),"rows":result}
        result1 = strHtml + "</tr></table>"
    except Exception as e:
        print result1
        print e[0]
    print result1
    return HttpResponse(result1)"""

